package com.lanou.moving.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lanou.moving.R;
import com.lanou.moving.activity.PlayMusicActivity;
import com.lanou.moving.adapter.SingerSongAdapter;
import com.lanou.moving.base.BaseFragment;
import com.lanou.moving.constant.URL;
import com.lanou.moving.entity.MusicInfo;
import com.lanou.moving.entity.SingerSong;
import com.lanou.moving.entity.dao.Collection;
import com.lanou.moving.entity.dao.CollectionDao;
import com.lanou.moving.entity.dao.RecentlyPlay;
import com.lanou.moving.entity.dao.RecentlyPlayDao;
import com.lanou.moving.eventBus.MyEventBus;
import com.lanou.moving.service.DownloadServices;
import com.lanou.moving.singleton.DaoSingleton;
import com.lanou.moving.view.CDSPopupWindow;
import com.lanou.moving.view.CommonProgressDialog;
import com.lanou.moving.volley.StringRequestUtf;
import com.lanou.moving.volley.VolleySingleton;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by dllo on 15/10/24.
 */
public class SingerSongFragment extends BaseFragment implements AdapterView.OnItemClickListener, SingerSongAdapter.OnMenuClickListener {
    private ListView singer_song_listview;
    private StringRequestUtf request;
    private VolleySingleton volleySingleton;
    private int singer_id;
    private SingerSongAdapter adapter;
    private List<SingerSong.DataEntity> songs;
    private View view;
    //数据库表
    private CollectionDao collectionDao;
    private View views;
    private TextView collect_tv;
    private ImageView rankingListBackground;
    private List<Collection> collections;
    private CDSPopupWindow pw;
    private RecentlyPlayDao recentlyPlayDao;
    private int index = 100;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_singer_song, null);
        singer_song_listview = (ListView) view.findViewById(R.id.singer_song_listview);
        singer_song_listview.setOnItemClickListener(this);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        volleySingleton = VolleySingleton.getInstance(mContext);
        collectionDao = DaoSingleton.getInstance().getCollectionDao();
        recentlyPlayDao = DaoSingleton.getInstance().getRecentlyPlayDao();

        Bundle bundle = getArguments();
        singer_id = bundle.getInt("singer_id");
        views = LayoutInflater.from(mContext).inflate(R.layout.layout_song, null);
        collect_tv = (TextView) views.findViewById(R.id.layout_song_collection);
        rankingListBackground = (ImageView) getActivity().findViewById(R.id.singer_detail_background);
        getData();
    }

    private void getData() {
        String url = URL.SINGER_SONG_START + singer_id + URL.SINGER_SONG_END;
        request = new StringRequestUtf(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                SingerSong singerSong = gson.fromJson(response, SingerSong.class);
                songs = singerSong.getData();
                adapter = new SingerSongAdapter(mContext, songs);
                adapter.setOnMenuClickListener(SingerSongFragment.this);
                singer_song_listview.setAdapter(adapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        volleySingleton.addQueue(request);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        SingerSong.DataEntity songsEntity = (SingerSong.DataEntity) parent.getItemAtPosition(position);
        if (!(songsEntity.getUrlList() != null && songsEntity.getUrlList().size() > 0)) {
            Toast.makeText(mContext, "暂时无法播放此歌曲", Toast.LENGTH_LONG).show();
        } else {
            RecentlyPlay recentlyPlay = new RecentlyPlay();
            recentlyPlay.setSongName(songsEntity.getName());
            recentlyPlay.setSingerName(songsEntity.getSingerName());
            recentlyPlay.setDuration(songsEntity.getUrlList().get(0).getDuration());
            recentlyPlay.setPlayUrl(songsEntity.getUrlList().get(0).getUrl());
            recentlyPlay.setSongId((long) songsEntity.getSongId());
            recentlyPlay.setResource("网络");
            recentlyPlayDao.insertOrReplace(recentlyPlay);

            List<MusicInfo> musicInfoList = new ArrayList<>();

            for (SingerSong.DataEntity entity : songs) {
                if (entity.getUrlList() != null && entity.getUrlList().size() > 0) {
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setSongName(entity.getName());
                    musicInfo.setAlbum(entity.getAlbumName());
                    musicInfo.setAlbumId((int) entity.getAlbumId());
                    musicInfo.setDuration(entity.getUrlList().get(0).getDuration());
                    musicInfo.setUrl(entity.getUrlList().get(0).getUrl());
                    musicInfo.setSingerName(entity.getSingerName());
                    musicInfo.setResouce("网络");
                    musicInfoList.add(musicInfo);
                }
            }

            Intent intent = new Intent(mContext, PlayMusicActivity.class);
            EventBus.getDefault().post(new MyEventBus.Deliver(musicInfoList, songsEntity.getName()));
            intent.putExtra("songName", songsEntity.getName());
            intent.putExtra("duration", songsEntity.getUrlList().get(0).getDuration());
            intent.putExtra("resource", "网络");
            intent.putExtra("albumId", songsEntity.getAlbumId());
            intent.putExtra("singerName", songsEntity.getSingerName());
            startActivity(intent);
        }
    }

    @Override
    public void onMenuClick(final SingerSong.DataEntity songsEntity) {
        rankingListBackground.setVisibility(View.VISIBLE);
        collections = collectionDao.queryBuilder().where(
                CollectionDao.Properties.SongId.eq(songsEntity.getSongId())).list();
        if (collections != null && collections.size() > 0) {
            collect_tv.setText("取消收藏");
        } else {
            collect_tv.setText("收藏");
        }
        pw = new CDSPopupWindow(mContext, views, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.layout_song_collection:
                        if ("收藏".equals(collect_tv.getText())) {
                            Collection collection = new Collection();
                            collection.setSongId(songsEntity.getSongId());
                            collection.setSongName(songsEntity.getName());
                            collection.setPlayUrl(songsEntity.getUrlList().get(0).getUrl());
                            collection.setAlbumId((int) songsEntity.getAlbumId());
                            collection.setDuration(songsEntity.getUrlList().get(0).getDuration());
                            collection.setSingerName(songsEntity.getSingerName());
                            collectionDao.insert(collection);
                            collect_tv.setText("取消收藏");
                            Toast.makeText(mContext, "已收藏", Toast.LENGTH_LONG).show();
                            pw.dismiss();
                        } else if ("取消收藏".equals(collect_tv.getText())) {
                            collectionDao.queryBuilder().where(CollectionDao.Properties.SongId
                                    .eq(songsEntity.getSongId())).buildDelete()
                                    .executeDeleteWithoutDetachingEntities();
                            collect_tv.setText("收藏");
                            Toast.makeText(mContext, "已取消收藏", Toast.LENGTH_LONG).show();
                            pw.dismiss();
                        }
                        break;
                    case R.id.layout_song_download:
                        if (songsEntity.getAuditionList() == null ||
                                songsEntity.getAuditionList().size() == 0 ||
                                songsEntity.getAuditionList().size() == 1) {
                            Toast.makeText(getActivity(), "暂无资源", Toast.LENGTH_LONG).show();

                        } else if (songsEntity.getAuditionList().size() > 1) {
                            String download_url = songsEntity.getAuditionList().get(1).getUrl();
                            startDownloadService(index, download_url, songsEntity.getName(), songsEntity.getSingerName());
                            index++;
                            pw.dismiss();
                        }
                        break;
                    case R.id.layout_song_share:
                        break;
                }

            }
        }, rankingListBackground);
        pw.showAtLocation(view.findViewById(R.id.singer_song_listview), Gravity.CENTER, 0, 0);
    }
    private void startDownloadService(int notifyId, String url, String songName, String singerName) {     //绑定服务类
        Intent intent = new Intent(getActivity(), DownloadServices.class);
        intent.putExtra("url", url);
        intent.putExtra("singerName", singerName);
        intent.putExtra("songName", songName);
        intent.putExtra("notifyId", notifyId);
        getActivity().startService(intent);
    }
}

